import React, { FC } from 'react';
import { css } from 'emotion';
import { Descendant, Transforms, Node } from 'slate';

import { CodeElement, CustomEditor, RenderElementPropsAttributes } from '../slate';

export const withCodeBlock = (editor: CustomEditor) => {
  const { normalizeNode } = editor;

  editor.normalizeNode = ([node, path]) => {
    if (path.length === 0) {
      // 在顶层，将 CodeBlock 合并
      for (const [child, childPath] of Node.children(editor, path)) {
        const [index] = childPath;
        if (index === 0) continue;
        const lastChild = Node.get(editor, [index - 1]) as Descendant;
        if (lastChild.type === 'codeBlock' && child.type === 'codeBlock') {
          Transforms.mergeNodes(editor, { at: childPath });
          Transforms.insertText(editor, '\n', { at: [index - 1, 1] });
        }
      }
    }

    return normalizeNode([node, path]);
  };

  return editor;
};

interface CodeBlockElementProps {
  attributes: RenderElementPropsAttributes;
  element: CodeElement;
}

export const CodeBlock: FC<CodeBlockElementProps> = ({ attributes, children, element }) => {
  return (
    <div
      {...attributes}
      className={css`
        font-family: monospace;
        background: hsla(0, 0%, 100%, 0.5);
        border: red solid 1px;
      `}
    >
      {children}
    </div>
  );
};
